<template>
	<view class="content">
		<nav-top :showType='1'></nav-top>
		<view class="content-title">
			<view>
				店员管理
			</view>
			<view class="content-title-rt">
				<van-button plain hairline type="primary" size="small" @click="onClickAdd">添加成员</van-button>
			</view>
		</view>
		<view class="content-box">
			<view class="item-box">
				<view>姓名</view>
				<view>手机号</view>
				<view>操作</view>
			</view>
			<!-- <view class="item-box shadow">
				<view>店员A</view>
				<view class="border-box">13107392696</view>
				<view class="border-box" @click="onClickEdit"><text>编辑</text></view>
			</view> -->
			<view class="item-box shadow" v-for="item in listData">
				<view>{{ item.nickName }}</view>
				<view class="border-box">{{ item.userName }}</view>
				<view class="border-box" @click="onClickEdit(item)"><text>编辑</text></view>
			</view>
		</view>
		<!-- 添加员工弹窗 -->
		<van-popup v-model:show="showAdd" round :style="{ padding: '20px' }">
			<van-form @submit="onSubmit">
				<van-cell-group inset>
					<van-field v-model="fromData.username" name="姓名" label="姓名" placeholder="请输入名称"
						:rules="[{ required: true, message: '请填写姓名' }]" />
					<van-field v-model="fromData.tel" type="tel" name="手机号" maxlength="11" label="手机号" placeholder="请输入手机号"
						:rules="rulesName" />
				</van-cell-group>
				<view class="qr-code" @click="onClickShowDown" v-if="showCode">
					下载二维码
					<!-- <canvas>
						<img :src="'../../static/img/sj.png'" width="100%" height="100%" style="-webkit-touch-callout: default;" />
					</canvas> -->
				</view>
				<van-row>
					<van-col span="10" v-if="!flag">
						<van-button round block type="danger" @click="onClickDel">
							删除
						</van-button>
					</van-col>
					<van-col :span="!flag ? 10 : 16" offset="4">
						<van-button round block type="primary" native-type="submit">
							确认{{ flag ? '添加' : '修改' }}
						</van-button>
					</van-col>
				</van-row>
			</van-form>
		</van-popup>
		<!-- <van-image-preview v-model:show="show" :images="images" @change="onChange">
			<template v-slot:index>
				<canvas>
					<img :src="images[index]" width="100%" height="100%" style="-webkit-touch-callout: default;" />
				</canvas>
			</template>

		</van-image-preview> -->
		<van-popup v-model:show="show" :style="{width: '94%',height: '80%' }">

			<!-- <canvas>
					<img :src="'../../static/img/code.png'" width="100%" height="100%" style="-webkit-touch-callout: default;" />
				</canvas> -->
			<!-- <uqrcode ref="uqrcode" canvas-id="qrcode" value="https://uqrcode.cn/doc"
					:options="{ margin: 10 ,backgroundImageSrc: ''}"></uqrcode> -->
			<van-swipe :show-indicators="false">
				<van-swipe-item>
					<view class="pop-code">
						<canvas id="shareCanvas" canvas-id="shareCanvas" style="width: 360px;height: 510px;">
							<img :src="canvasUrl" style="-webkit-touch-callout: default;">
						</canvas>
						<view class="">
							长按保存图片
						</view>
					</view>
				</van-swipe-item>
				<van-swipe-item>
					<view class="pop-code">
						<canvas style="width: 360px;height: 510px;">
							<view style="width: 100%;height: 100%;display: flex; align-items: center; justify-content: center;">
								<img :src="shareCodeImage2" style="-webkit-touch-callout: default; width: 200px;height: 200px;">
							</view>
						</canvas>
						<view class="">
							长按保存图片
						</view>
					</view>
				</van-swipe-item>
			</van-swipe>
			<view style="width: 0;height: 0;overflow: hidden;">
				<canvas id="qrcode" canvas-id="qrcode" style="width: 736rpx;height: 1460rpx;"></canvas>
				<canvas id="qrcode" canvas-id="qrcode2" style="width: 736rpx;height: 1460rpx;"></canvas>
			</view>
		</van-popup>
		<van-popup v-model:show="showPicker" round position="bottom">
			<van-picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
		</van-popup>
	</view>
</template>

<script>
	import {
		reactive,
		toRefs,
		watchEffect,
		onMounted
	} from 'vue'
	import UQRCode from "uqrcodejs";
	import NavTop from '@/components/NavTop.vue'
	import api from '@/api/staff.js'
	import $store from "@/store";
	import uqrcode from '@/uni_modules/uv-qrcode/components/uv-qrcode/uv-qrcode.vue'
	import {
		showConfirmDialog
	} from 'vant';
	export default {
		props: {},
		components: {
			NavTop,
			uqrcode
		},
		setup(props, ctx) {
			const data = reactive({
				showCode: false,
				show: false,
				index: 0,
				listData: [],
				flag: false,
				showPicker: false,
				showAdd: false,
				columns: [{
						text: '店长',
						value: 'dianzhang'
					},
					{
						text: '店员',
						value: 'dianyuan'
					}
				],
				fromData: {
					username: '',
					tel: '',
					role: ''
				},
				rulesName: [{
						required: true,
						message: '请输入手机号码'
					},
					{
						pattern: /^1[3-9]\d{9}$/,
						message: '手机号码格式错误'
					}
				],
				userId: '',
				imageSrc: 'https://example.com/path/to/image.jpg', // 图片地址
				longPressThreshold: 500, // 长按的阈值，单位是毫秒
				isLongPress: false, // 是否长按的标志
				touchStartTime: 0, // 触摸开始的时间
				shareCodeImage: '',
				shareCodeImage2: '',
				canvasUrl: ""
			})
			// 
			// 获取员工列表
			const getList = () => {
				api.list({}).then(res => {
					res.rows.forEach(val => {
						data.listData.push(val)
					})
				})
			}
			const createShareImage = () => {
				let context = uni.createCanvasContext("shareCanvas");
				// let imageWidthInRpx = 368; // 图片宽度
				// let imageHeightInRpx = 498; // 图片高度
				let imageWidthInRpx; // 图片宽度
				let imageHeightInRpx; // 图片高度
				uni.createSelectorQuery().select('#shareCanvas').boundingClientRect(function(rect) {
					// console.log('元素高度：', rect);
					imageWidthInRpx = rect.width;
					imageHeightInRpx = rect.height;
				}).exec();
				// 图片的rpx大小

				// 绘制图片到Canvas上
				context.drawImage(
					"../../static/img/code_img.png",
					0,
					0,
					imageWidthInRpx,
					imageHeightInRpx
				);

				context.save()
				let xset = imageWidthInRpx / 2 - 156 / 2
				// let yset = imageHeightInRpx / 2 - 186 / 2

				context.drawImage(
					data.shareCodeImage,
					xset,
					150,
					176,
					176
				)

				// context.save()
				context.setFontSize(20)
				context.setFillStyle('#000');
				context.setTextAlign('left') //文本水平居中
				context.fillText($store.state.areaText, 92, 80)
				// context.draw()
				context.save()
				context.draw()

				setTimeout(() => {
					uni.canvasToTempFilePath({
						canvasId: 'shareCanvas',
						width: imageWidthInRpx,
						height: imageHeightInRpx,
						destWidth: imageWidthInRpx,
						destHeight: imageHeightInRpx,
						success: (res) => {
							// uni.hideLoading()
							// data.show = true
							data.canvasUrl = res.tempFilePath
						}
					})
				}, 300);
			}
			const createdImg = () => {
				// let widths;
				// let heights;
				// // uni.getSystemInfo({
				// // 		success(res) {
				// // 			console.log(res.screenWidth) //屏幕宽度
				// // 			console.log(res.screenHeight) //屏幕高度
				// // 			widths = res.screenWidth
				// // 			heights = res.screenHeight
				// // 		})
				// // 	.exec()
				// // })

				// uni.getSystemInfo({
				// 	success: function(res) {
				// 		// const windowWidth = res.windowWidth;   // 窗口宽度
				// 		// const windowHeight = res.windowHeight; // 窗口高度
				// 		widths = res.windowWidth
				// 		heights = res.windowHeight
				// 	}
				// });
				var qr = new UQRCode();
				// 设置二维码内容
				qr.data = `https://payhub.jinmi.lengshan.com.cn/gasmate?mch_id=${$store.state.areaId}&emp_id=${uni.getStorageSync('userInfo').userId}`;
				// 设置二维码大小，必须与canvas设置的宽高一致
				qr.size = 180;
				qr.useDynamicSize = true;
				qr.sizeUnit = 'rpx';

				qr.dynamicSize = 180;
				// 调用制作二维码方法
				qr.make();

				// 获取canvas上下文
				var canvasContext = uni.createCanvasContext("qrcode"); // 如果是组件，this必须传入
				qr.canvasContext = canvasContext;
				// 获取canvas上下文
				qr.drawCanvas().then(() => {
					// setTimeout(() => {

					// }, 300);
					uni.canvasToTempFilePath({
						canvasId: 'qrcode',
						width: 200,
						height: 200,
						success: res => {
							data.shareCodeImage = res.tempFilePath
							// console.log(data.shareCodeImage, 'this.shareCodeImage')
							createShareImage()
						},
						fail: err => {
							console.log(err);
						}
					})
				})
				var qr2 = new UQRCode();
				qr2.data = `https://payhub.jinmi.lengshan.com.cn/general?mch_id=${$store.state.areaId}`;
				// console.log(qr2.data,'qr2.data')
				// 设置二维码大小，必须与canvas设置的宽高一致
				qr2.size = 180;
				qr2.useDynamicSize = true;
				qr2.sizeUnit = 'rpx';
				
				qr2.dynamicSize = 180;
				// 调用制作二维码方法
				qr2.make();
				var canvasContexts = uni.createCanvasContext("qrcode2"); // 如果是组件，this必须传入
				qr2.canvasContext = canvasContexts;
				// 调用绘制方法将二维码图案绘制到canvas上
				qr2.drawCanvas().then(() => {
					uni.canvasToTempFilePath({
						canvasId: 'qrcode2',
						width: 200,
						height: 200,
						success: res => {
							data.shareCodeImage2 = res.tempFilePath
							// console.log(data.shareCodeImage, 'this.shareCodeImage')
							createShareImage()
						},
						fail: err => {
							console.log(err);
						}
					})
				})
			}
			onMounted(() => {
				getList()
				data.showCode = true
				if (uni.getStorageSync('userInfo').roleCode.indexOf('yuangong') !== -1) {
					data.showCode = true
				}
			})
			const onChange = (newIndex) => {
				data.index = newIndex;
			}
			watchEffect(() => {
				data.funcDatas = props.funcData
			})
			const onConfirm = ({
				selectedOptions
			}) => {
				data.fromData.role = selectedOptions[0].text
				data.showPicker = false;
			};
			const onClickDel = () => {
				showConfirmDialog({
						title: '删除店员',
						message: '确认删除？',
					})
					.then(() => {
						api.remove({
							userIds: data.userId
						}).then(res => {
							data.listData = [];
							getList()
							data.showAdd = false
							uni.showToast({
								title: '删除成功',
								icon: 'none'
							})
						})
						// on confirm
					})
					.catch(() => {
						// on cancel
					});
			}
			// 添加成员
			const onClickAdd = () => {
				data.fromData.username = ''
				data.fromData.tel = ''
				data.userId = ''
				data.showAdd = true
				data.flag = true
			}
			const onClickEdit = (item) => {
				data.fromData.username = item.nickName
				data.fromData.tel = item.userName
				data.userId = item.userId
				data.showAdd = true
				data.flag = false
			}
			const onSubmit = () => {
				// 提交
				if (data.flag) {
					api.user({
						deptId: $store.state.areaId, // 加油站id
						userName: data.fromData.tel, // 手机号
						nickName: data.fromData.username, //姓名
						password: "123456", //密码默认123456	
						status: 0, //默认打开状态
						postIds: [],
						roleIds: [2]
					}).then(res => {
						data.listData = [];
						getList()
						data.showAdd = false
						uni.showToast({
							title: '添加成功',
							icon: 'none'
						})
					})
				} else {
					api.edit({
						deptId: $store.state.areaId, // 加油站id
						userName: data.fromData.tel, // 手机号
						nickName: data.fromData.username, //姓名
						userId: data.userId
					}).then(res => {
						data.listData = [];
						getList()
						data.showAdd = false
						uni.showToast({
							title: '修改成功',
							icon: 'none'
						})
					})
				}
			}
			const onClickShowDown = () => {
				data.show = true;
				setTimeout(()=>{
				  createdImg();
					
				},300)
			}
			return {
				...toRefs(data),
				onConfirm,
				onClickAdd,
				onClickDel,
				onSubmit,
				onClickEdit,
				onChange,
				onClickShowDown
			}
		}
	}
</script>

<style lang="less" scoped>
	.content {
		width: 100%;
		height: 100vh;
		overflow: hidden;

		.van-popup--center {
			max-width: 1200px;
		}

		.content-title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 32rpx;
			text-indent: 20rpx;
			margin-top: 20rpx;

			.content-title-rt {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				text-align: left;
				margin-right: 40rpx;

				text {
					display: block;
					text-indent: 10rpx;
				}
			}
		}

		.content-box {
			width: 100%;
			padding: 40rpx 20rpx 0;
			box-sizing: border-box;

			.item-box {
				display: flex;
				align-items: center;
				justify-content: space-around;
				margin-top: 20rpx;
				text-align: center;
				border-radius: 10rpx;
				font-size: 26rpx;

				&:first-child {
					font-size: 30rpx;
				}

				&>view {
					width: 30%;
				}

				.border-box {
					display: flex;
					justify-content: center;
					// width: 18%;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 22rpx;

					text {
						color: rgb(228, 132, 132);
					}

					.van-cell {
						padding: 0;
					}
				}
			}

			.shadow {
				box-shadow: 0 0 22rpx 0 rgba(0, 0, 0, .1);
			}
		}

		.qr-code {
			width: 100%%;
			// height: 200rpx;
			// font-size: 20rpx;
			// text-align: center;
			margin: 80rpx 0;
			display: flex;
			justify-content: center;

			canvas {
				width: 200rpx;
				// height: 200rpx;
			}

			img {
				width: 200rpx;
				// height: 200rpx;
				margin: 0 auto;
			}
		}

		.pop-code {
			width: 100%;
			height: 100%;
			// font-size: 20rpx;
			// text-align: center;
			// margin: 80rpx 0;
			display: flex;
			justify-content: center;
			flex-wrap: wrap;

			// canvas {
			// 	width: 100%;
			// 	height: 100%;
			// }

			// img {
			// 	width: 600rpx;
			// 	height: 600rpx;
			// 	margin: 0 auto;
			// }
		}
	}
</style>